package com.itheima.youdianda.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.dto.PageDto;
import com.itheima.youdianda.mapper.SysRoleMapper;
import com.itheima.youdianda.pojo.SysMenu;
import com.itheima.youdianda.pojo.SysRole;
import com.itheima.youdianda.pojo.SysRoleMenu;
import com.itheima.youdianda.service.SysMenuService;
import com.itheima.youdianda.service.SysRoleMenuService;
import com.itheima.youdianda.service.SysRoleService;
import com.itheima.youdianda.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysMenuService sysMenuService;

    @Override  //GET 角色列表-分页
    public R listSysRole(String page, String limit, String name) {
        //获得分页SysRole数据
        Page<SysRole> pageInfo = new Page<SysRole>(Convert.toLong(page), Convert.toLong(limit));
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(name),SysRole::getName,name);
        wrapper.eq(SysRole::getDelFlag,"0");//筛选未被删除的角色
        wrapper.orderByDesc(SysRole::getUpdateDate);
        pageInfo = page(pageInfo,wrapper);

        //页面中每条sys_role数据
        List<SysRole> records = pageInfo.getRecords();

        //查询sys_role_menu并添加进每条sys_role数据中
        for (SysRole record : records) {
            //获取每条角色id
            String roleId = record.getId();
            //查询每个角色对应权限菜单id的list
            LambdaQueryWrapper<SysRoleMenu> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(SysRoleMenu::getRoleId,roleId);
            List<SysRoleMenu> sysRoleMenuList = sysRoleMenuService.list(wrapper1);
                //从list中遍历提取role_menus,role_id并加入每个record模型
            String role_menus = "";
            for (int i = 0; i < sysRoleMenuList.size(); i++) {
                if (i<sysRoleMenuList.size()-1){
                    String menuId = sysRoleMenuList.get(i).getMenuId();
                    role_menus = role_menus + menuId+",";
                }else {
                    role_menus = role_menus + sysRoleMenuList.get(i).getMenuId();
                }
            }
            //Role_id唯一,设定一次,role_menus为拼接的字符串,也只设置一次
            record.setRole_id(roleId);
            record.setRole_menus(role_menus);
            record.setCreateDate(LocalDateTime.now());
        }
        //要返回的最终页面对象
        PageDto pageDto = new PageDto();
        pageDto.setCurrentPage(Convert.toLong(page)); //已有传参:当前页数
        pageDto.setPageSize(Convert.toLong(limit)); //已有传参:每页条数
        pageDto.setCount(pageInfo.getTotal());   //查询结果总条数
        pageDto.setTotalPages(pageInfo.getPages());  //查询结果总页数
        pageDto.setData(records);

        return R.success(pageDto);
    }


    @Override //GET 角色详情
    public R rowInfo(String id) {
        SysRole sysRole = getById(id);

        //提取对应menuIds
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId,id);
        List<SysRoleMenu> sysRoleMenuList = sysRoleMenuService.list(wrapper);
        //将上面roleMenu对象提取出menuId塞进集合menuIdlist
        ArrayList<Integer> menuIdlist = new ArrayList<>();
        for (SysRoleMenu sysRoleMenu : sysRoleMenuList) {
            menuIdlist.add(Integer.parseInt(sysRoleMenu.getMenuId()));
        }

        //查看pid==0的id对应menu
        LambdaQueryWrapper<SysMenu> menuWrapper = new LambdaQueryWrapper<>();
        menuWrapper.in(SysMenu::getId,menuIdlist);
        menuWrapper.eq(SysMenu::getPid,0);
        List<SysMenu> menuList = sysMenuService.list(menuWrapper);
        sysRole.setAuthList(menuList);

        return R.success(sysRole);
    }

    @Override  //POST 角色修改
    public void updateSysRole(SysRole sysRole) {
        log.info("要修改的sysrole{}",sysRole);
        sysRole.setUpdateDate(LocalDateTime.now());
        updateById(sysRole);
        //更新sysRole_menu:先删除原先role_id对应数据
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId,sysRole.getId());
        sysRoleMenuService.remove(wrapper);

        //要添加的menuids字符串集合List
        List<String> menuids = sysRole.getMenuids();
        //遍历集合,添加进sysRoleMenu表格中
        for (String menuid : menuids) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(sysRole.getId());
            sysRoleMenu.setMenuId(menuid);
            sysRoleMenuService.save(sysRoleMenu);
        }
        /*sysRoleMenuService.saveBatch();*/
    }

    @Override  //GET 角色删除
    public void delete(String id) {
        removeById(id);
        //删除对应menuIds
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId,id);
        sysRoleMenuService.remove(wrapper);
    }

    @Override  //POST 角色添加
    public void add(Map<String,Object> map) {
        String name = (String) map.get("name");
        String description = (String) map.get("description");
        List<Integer> menuids = (List) map.get("menuids");

        //要添加的角色模型,把传参加进去
        SysRole sysRole = new SysRole();
        sysRole.setName(name);
        sysRole.setDescription(description);
        sysRole.setCreateDate(LocalDateTime.now());
        save(sysRole);

        //添加menuIds进sysRoleMenu表格
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        String roleId = sysRole.getId();
        for (Integer menuid : menuids) {
            sysRoleMenu.setMenuId(Convert.toStr(menuid));
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenuService.save(sysRoleMenu);
        }
    }




}
